import React, { PureComponent, Component } from 'react'
import './App.css'
export default class App extends PureComponent {
    constructor () {
        super()
        this.state = {
            todos: [
                {
                    id:1,
                    isCompleted:false,
                    content:'你说的嘛，偶像？'
                },
                {
                    id:2,
                    isCompleted:true,
                    content:'All is well'
                },
                {
                    id:3,
                    isCompleted:false,
                    content:'Take me alone, please'
                }
            ],
            entryValue: '',  //输入内容
            leftNum: 0, // items left
            isAllChecked: true, // 全选
            doubleClickId: '',  //双击Id
            hash:'#/'
        }
        
    }

    componentDidMount () {
        window.addEventListener('hashchange', e => {this.setHash()})
        window.addEventListener('beforeunload', () => {
            sessionStorage.setItem('todosSession', JSON.stringify(this.state.todos))
        })

        let todos = JSON.parse(sessionStorage.getItem('todosSession'))
        if (todos) {
            this.state.todos = todos
        }
        this.diffItemsLeft()
        this.setHash()

        
    }

    componentWillUnmount () {
        // 缓存列表数据
        
        window.removeEventListener('hashchange', e => {this.setHash()})   
    }

    // 1.渲染列表
    renderList () {
        const {hash} = this.state
        return this.state.todos.map ((todo,index) => {
            if (hash === '#/active' && todo.isCompleted)  return null;
            if (hash === '#/completed' && !todo.isCompleted)  return null;

            return (
                <li className="item" key={ todo.id }>
                    <input type="checkbox" checked={ todo.isCompleted } onChange={ (e) => this.handlerCheckBox(e,todo.id) }/>
                    <span className={'item-text ' + (todo.isCompleted ? 'item-completed' : '')} onDoubleClick={(e) => { this.handlerDoublleClick(todo) }}>{ todo.content }</span>
                    <button className="btn" onClick={(e) => this.handlerDelete(index)}>X</button>
                    <input type="text"
                    ref={'todo_' + todo.id}
                    className={ 'modify-input ' + (todo.id === this.state.doubleClickId ? 'double' : '') }
                    value={ todo.content }
                    onChange={ (e) => this.handlerChangeItem(e,todo)}
                    onKeyUp={ (e) => this.handlerItemkeyUp(e) }/>
                </li>
            )
        })
    }
    // 2.监听文本框输入
    handlerEntry (e) {
        this.setState({
            entryValue:e.target.value
        })
    }
    //3. enter 输入
    handlerEnter (e) {
        if (e.keyCode !== 13) return;
        if (!this.state.entryValue.trim()) return;
        const todos = [...this.state.todos]
        let lastId = this.state.todos[this.state.todos.length - 1].id;

        todos.push({
            id: lastId + 1,
            isCompleted: false,
            content: this.state.entryValue
        })
        this.setState({
            todos,
            entryValue:''
        },() => {
            this.diffItemsLeft()
        })
    
    }
    // 4. 删除列表某一项
    handlerDelete (idx) {
        const todos = [...this.state.todos]
        todos.splice(idx, 1)
        this.setState({
            todos
        }, () => {
            this.diffItemsLeft()
        })
    }
    // 5. 计算items left 
    diffItemsLeft () {
        const todos = [...this.state.todos]
        const list = todos.filter(todo => !todo.isCompleted)

        this.setState({
            leftNum: list.length,
            isAllChecked: !Boolean(list.length)
        })
    }
    // 6. 监听 checkbox 
    handlerCheckBox (e,id) {
        console.dir(e.target)
        const todos = [...this.state.todos];
        todos.forEach(todo => {
            if (id === todo.id) todo.isCompleted = e.target.checked
        })
        this.setState ({
            todos
        },() =>{
            this.diffItemsLeft()
        })
    }
    // 7. 监听全选
    handlerAllCheck (e) {
        const todos = [...this.state.todos];
        todos.forEach(todo => {
            todo.isCompleted = e.target.checked
        })
        this.setState({
            todos,
            isAllChecked: e.target.checked
        },() => {
            this.diffItemsLeft()
        })
    }
    // 8.监听双击事件
    handlerDoublleClick (todo) {
        this.setState({
            doubleClickId: todo.id
        },() => {
            this.refs['todo_' + todo.id].focus()
        })
    }
    // 9. 监听每个item input
    handlerChangeItem (e,todo) {
        const todos = [...this.state.todos]
        todos.forEach(item => {
            if ( item.id === todo.id ) item.content = e.target.value
        })
        this.setState({
            todos
        })
    }
    // 10. 监听item input  Enter事件
    handlerItemkeyUp (e) {
        if(e.keyCode !== 13) return;
        this.setState({
            doubleClickId: ''
        })
    }
    // 11. 清理所有已完成任务
    handlerClearCompleted () {
        let todos = [...this.state.todos];
        todos = todos.filter(todo => !todo.isCompleted);
        
        this.setState({
            todos
        })
    }
    // 12.筛选列表
    handlerOpetrate (e,hash) {
        // e.preventDefault()
        this.setState({
            hash
        })
    }
    // 13 设置hash
    setHash () {
        this.setState({
            hash: window.location.hash
        })
    }

    render () {
        const { entryValue } = this.state

        return <React.Fragment>
            <div className="wrap">
                <h1 className="title">todos</h1>
                <div className="content">
                {/* { <!-- 头部 -->} */}
                    <header className="header"> 
                        <input type="checkbox" checked={ this.state.isAllChecked } className="all-check" onChange={(e) => this.handlerAllCheck(e)}/>
                        <input type="text" 
                        placeholder="What needs to be done?" 
                        className="entry-input" 
                        value={ entryValue } 
                        onChange = {(e) => this.handlerEntry(e)} 
                        onKeyUp={e => this.handlerEnter(e)}
                        />
                    </header>
                    {/* {<!-- 主体 -->} */}
                    <section className="section">
                        <ul className="list">
                            { this.renderList() }
                        </ul>
                    </section>
                {/* { <!-- 尾部 -->} */}
                    <footer className="footer">
                        <span>{ this.state.leftNum } items left</span>
                        <div className="group">
                            <a href="#/" onClick={ (e) => this.handlerOpetrate(e,'#/') }>All</a>
                            <a href="#/active" onClick={ (e) => this.handlerOpetrate(e,'#/active') }>Active</a>
                            <a href="#/completed" onClick={ (e) => this.handlerOpetrate(e,'#/completed') }>Completed</a>
                        </div>
                        <span className="clear-completed" onClick={(e) => this.handlerClearCompleted(e)}>Clear completed</span>
                    </footer>
                </div>

            </div>
        </React.Fragment>
    }
}